package com.skytech.ssr.dynamicdb.config;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.aop.DynamicDataSourceAnnotationAdvisor;
import com.baomidou.dynamic.datasource.aop.DynamicDataSourceAnnotationInterceptor;
import com.baomidou.mybatisplus.autoconfigure.MybatisPlusProperties;
import com.baomidou.mybatisplus.extension.incrementer.H2KeyGenerator;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PerformanceInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@MapperScan(basePackages = {"com.skytech.ssr.dynamicdb.primary.domain.mappers", "com.skytech.ssr.dynamicdb.secondary.domain.mappers"})
public class MybatisPlusConfig {
    /**
     * mybatis-plus分页插件<br>
     * 文档：http://mp.baomidou.com<br>
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();

        return paginationInterceptor;
    }


    @Bean
    public H2KeyGenerator getH2KeyGenerator() {
        return new H2KeyGenerator();
    }

    /**
     * 性能分析拦截器，不建议生产使用
     */
    @Bean
    public PerformanceInterceptor performanceInterceptor() {
        return new PerformanceInterceptor();
    }

    @Bean
    public MybatisPlusProperties mybatisPlusProperties() {
        return new MybatisPlusProperties();
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory(@Qualifier("dynamicDataSource") DynamicRoutingDataSource dynamicDataSource,
                                               @Qualifier("mybatisPlusProperties") MybatisPlusProperties mybatisPlusProperties) throws Exception {
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        bean.setDataSource(dynamicDataSource);
        bean.setMapperLocations(mybatisPlusProperties.resolveMapperLocations());
        bean.setTypeAliasesPackage(mybatisPlusProperties.getTypeAliasesPackage());
        bean.setTypeEnumsPackage(mybatisPlusProperties.getTypeEnumsPackage());
        bean.setGlobalConfig(mybatisPlusProperties.getGlobalConfig());
        bean.setConfiguration(mybatisPlusProperties.getConfiguration());
        return bean.getObject();
    }

    @Bean
    public DynamicDataSourceAnnotationAdvisor dynamicDatasourceAnnotationAdvisor() {
        DynamicDataSourceAnnotationInterceptor dynamicInterceptor = new DynamicDataSourceAnnotationInterceptor();
        dynamicInterceptor.setDynamicAnnotationResolver(new MyAnnotationResolver());
        return new DynamicDataSourceAnnotationAdvisor(dynamicInterceptor);
    }

}
